import { BuildOptions, CSSOptions, ServerOptions } from "vite";

//开发选项
export function Server(env: Record<string, any>): ServerOptions {
    const opts: ServerOptions = {
        //主机，设置为true即是本机地址
        host: true,

        //设置运行端口号
        port: Number(env.VITE_PORT),

        //设为 true 时若端口已被占用则会直接退出，而不是尝试下一个可用端口
        strictPort: true,

        //是否开启https功能
        https: false,

        //运行成功后打开浏览器
        open: false,
    };

    return opts;
}

//打包构建选项
export function Build(env: Record<string, any>): BuildOptions {
    const opts: BuildOptions = {
        //打包输出路径
        outDir: env.VITE_OutDir,

        //设置混淆器方式，因为下面使用了terserOptions
        // minify: "terser",

        //打包时先清空目标目录
        emptyOutDir: true,

        //规定触发警告的 chunk 大小
        chunkSizeWarningLimit: 9999,

        //打包文件去掉console和debugger
        terserOptions: {
            compress: {
                drop_console: true,
                drop_debugger: true,
            },
        },

        //打包生成的代码只显示文件名，不加Hash后缀
        rollupOptions: {
            output: {
                entryFileNames: `assets/js/[name].js`,
                chunkFileNames: `assets/js/[name].js`,
                assetFileNames: `assets/ext/[name].[ext]`,
                manualChunks(id) {
                    if (id.includes("node_modules")) {
                        return id.toString().split("node_modules/")[1].split("/")[0].toString();
                    }
                },
            },
        },
    };

    return opts;
}

//css处理，在打包时不报@charset的警告
export function Css(): CSSOptions {
    const opts: CSSOptions = {
        postcss: {
            plugins: [
                {
                    postcssPlugin: "internal:charset-removal",
                    AtRule: {
                        charset: (atRule) => {
                            if (atRule.name === "charset") {
                                atRule.remove();
                            }
                        },
                    },
                },
            ],
        },
        preprocessorOptions: {
            scss: {
                additionalData: `@use "@/assets/css/element-var.scss" as *;`,
            },
        },
    };

    return opts;
}
